package com.lemon.boot.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.lemon.boot.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;

/**
 * @author 李猛
 * @datetime 2023/12/21 10:15
 * @description 类对象
 */
@Slf4j
public class EasyExcelUtil {
    /**
     * EasyExcel写
     *
     * @param response
     * @param clazz
     * @param fileName
     * @param sheet
     * @param data
     * @param <T>
     */
    public static <T> void write(HttpServletResponse response, Class<T> clazz, String fileName, String sheet, Collection<T> data) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        try {
            //这里URLEncoder.encode可以防止中文乱码
            String filename = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", fileName.endsWith(".xlsx") ? filename : String.format("%s.xlsx", filename));
            EasyExcel.write(response.getOutputStream(), clazz).excelType(ExcelTypeEnum.XLSX).sheet(sheet).doWrite(data);
        } catch (IOException e) {
            throw new CustomException(e.getMessage());
        }
    }
}
